<?php

namespace App\Services\BrokerageDivider;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class BrokerageDivider
{
	public function divide()
	{
		User::query()
			->where('grade', 'vip')
			->whereDate('created_at', '<', Carbon::today()->day(1))
			->chunkById(100, function (Collection $users) {
				
				if ($users->isEmpty()) return;
				
				foreach ($users as $user) {
					
					if ($user->brokerages()->doesntExist()) continue;
				
					app(BrokerageCashier::class)->settle($user);

					Log::debug("User: {$user->id} settled.");
					
					usleep(100);
				}
				
			});
	}
	
	public function run()
	{
		if (Carbon::today()->day !== 9) {
			
			return;
		}
		

		Log::info("Brokerage settlement started.");
		
		$this->divide();
		
		Log::info("Brokerage settlement ended.");
	}
}
